package service

import (
	"context"
	"saleforce/sf-backend-user/bootstrap"
	"saleforce/sf-backend-user/model"
	bs "saleforce/sf-common/protoc/backend-user"
	"saleforce/sf-common/utils"
)

type UserService struct {
	bs.UnimplementedUserServiceServer
}

func (u UserService) GetUser(c context.Context, p *bs.StringIdParam) (*bs.GetUserResp, error) {
	bootstrap.InitAll()
	user, err := model.User{}.GetById(p.Id)
	if err != nil {
		return nil, err
	}
	if user != nil {
		resp := bs.GetUserResp{}
		resp.User = &bs.User{
			Id:       user.Id,
			Username: user.Username,
			Nickname: user.Nickname,
			UserType: user.UserType,
			Status:   user.Status,
		}
		rid := resp.User.GetRoleId()
		role, _ := model.Role{}.GetById(rid)
		resp.Role = &bs.Role{
			Id:       role.Id,
			RoleName: role.RoleName,
			Status:   role.Status,
			Menus:    role.Menus,
			IsSys:    role.IsSys,
		}
		slice, _ := utils.StringToIntSlice[int64](role.Menus)
		menus, _ := model.MenuModel{}.ListByIds(slice)
		resp.Menus = []*bs.Menu{}
		for _, m := range menus {
			resp.Menus = append(resp.Menus, &bs.Menu{
				Id:       m.Id,
				Name:     m.Name,
				Status:   m.Status,
				MenuType: m.MenuType,
				IsShow:   m.IsShow,
				ParentId: m.ParentId,
			})
		}
		depExts, _ := model.DepartmentExtModel{}.GetRelationsByUserId(user.Id)
		extMap := make(map[int64]model.DepartmentExtModel)
		depIds := []int64{}
		for _, ext := range depExts {
			extMap[ext.DepId] = ext
			depIds = append(depIds, ext.DepId)
		}
		deps, _ := model.DepartmentModel{}.ListByIds(depIds)
		resp.Departments = []*bs.Department{}
		for _, d := range deps {
			resp.Departments = append(resp.Departments, &bs.Department{
				Id:          d.Id,
				ExtId:       extMap[d.Id].Id,
				Name:        d.Name,
				Status:      d.Status,
				ParentId:    d.ParentId,
				WorkNo:      extMap[d.Id].WorkNo,
				Position:    extMap[d.Id].Position,
				Description: extMap[d.Id].Description,
			})
		}
		return &resp, nil
	}
	return nil, nil
}
